L1-050 倒数第N个字符串
题目 L1-050 倒数第N个字符串
思路分析
将字符串作为26进制的数 与10进制相互转换
代码实现
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
using ll = long long;
using ull = unsigned long long;
using PII = pair<int, int>;
using Pll = pair<ll, ll>;
int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };
const int inf = 0x3f3f3f3f;
ll qmi(ll a,ll k) {
ll res=1;
while(k) {
if(k&1) res=res*a;
k>>=1;
a=a*a;
}
return res;
}
signed main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int l;
cin>>l;
int n;
cin>>n;
ll end=0;
// for(int i=0;i<l;i++){
// end+=25*pow(26,i);
// }
for (int i = 0; i < l; i++) {
end += 25 * qmi(26, i);
}
ll idx=end-n+1;
stack<char> ans;
while(idx){
ans.push('a'+(idx%26));
idx/=26;
}
while(ans.size()<l){
ans.push('a');
}
while(!ans.empty()) {
cout<<ans.top();
ans.pop();
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
using ll = long long;
using ull = unsigned long long;
using PII = pair<int, int>;
using Pll = pair<ll, ll>;
int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };
const int inf = 0x3f3f3f3f;
ll qmi(ll a,ll k) {
ll res=1;
while(k) {
if(k&1) res=res*a;
k>>=1;
a=a*a;
}
return res;
}
signed main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int l;
cin>>l;
int n;
cin>>n;
ll end=0;
// for(int i=0;i<l;i++){
// end+=25*pow(26,i);
// }
for (int i = 0; i < l; i++) {
end += 25 * qmi(26, i);
}
ll idx=end-n+1;
stack<char> ans;
for(int i = 0; i < l; ++i){
ans.push('a'+(idx%26));
idx/=26;
}
while(!ans.empty()) {
cout<<ans.top();
ans.pop();
}
return 0;
}
同类题型
视频讲解
⬅️ L1-049 天梯赛座位分配 🏠 00-天梯赛 ➡️ L1-051 打折
💬 评论